#include <time.h>
#include "sysdef.h"
#include "logger.h"

int exe_exit(const char* desc)
{
    LOG_NOTICE(GET_SYS_LOG(), "%s\n", desc);

    exit(0);
}

int sys_rand()
{
    srand((uint)time(NULL));

#if defined(RAND_MAX) && RAND_MAX <= 0xFFFF
    return ((rand()&0xFFFF)<<16) | (rand()&0xFFFF);
#else
    return rand();
#endif
}

int get_cpu_count()
{
#ifdef WIN32
    return 1;
#else
    return sysconf(_SC_NPROCESSORS_CONF);
#endif;    
}

void sleep_s(int sec)
{
#ifdef WIN32
    Sleep(sec * 1000);
#else
    sleep(sec);
#endif
}

void sleep_ms(int msec)
{
#ifdef WIN32
    Sleep(msec);
#else
    usleep(msec * 1000);
#endif
}

uint get_tick_count()//uint64--->WIN32:%I64u,LINUX:%llu
{
#ifdef WIN32
    return GetTickCount();
#else
    struct timeb tp;
    ftime(&tp);
    return tp.time*1000 + tp.millitm;

    //struct timeval tv;
	//gettimeofday(&tv, NULL);
	//return tv.tv_sec*1000 + tv.tv_usec/1000;
#endif
}

char* get_cur_time(char* outbuf, int outlen)
{
    time_t now = time(NULL);
    struct tm* timeinfo;;

#ifdef WIN32
    timeinfo = localtime(&now);
#else
    struct tm t;
    timeinfo = localtime_r(&now, &t);
#endif

    snprintf(outbuf, outlen, "%04d-%02d-%02d %02d:%02d:%02d",timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);

    return outbuf;
}

int arg_desc(char* outbuf, int outlen, char* msg, ...)
{
    int size;
    va_list args;
    va_start(args, msg);
    size = vsnprintf(outbuf, outlen-1, msg, args);
    va_end(args);

    return size;
}
